<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;


class AdminService
{
    public static function adminHomeData(Model $model, string $key, int $days)
    {
        $key = sprintf($key, $days);
        return Cache::remember($key, now()->endOfDay(), function () use ($days, $model) {
            $end_day = now()->subDay()->endOfDay();

            $data = $model::query()->whereBetween('created_at', [now()->subDays($days)->startOfDay(), $end_day])
                ->select('created_at')->get();
            $list = [];
            for ($i = $days; $i > 0; $i--) {
                $list[] = $data->whereBetween('created_at', [now()->subDays($i)->startOfDay(), now()->subDays($i)->endOfDay()])->count();
            }
            return [
                'list' => $list,
                'total' => count($data)
            ];
        });
    }
}
